Skip to content

Conversation

chris-chambers
Copy link

Tasks created following the polling example given in complex async workflows can't be canceled by listenerMiddleware.clearListeners. Any time a listener is unsubscribed before it has finished running, this condition can occur.

This PR updates listener middlewares to explicitly track executing listeners (which may or may not be unsubscribed), so that cancelation can happen in all cases.


Here's a small reproduction, based on the example from the docs (there are a couple more scenarios in the accompanying tests):

const eventPollingStarted = createAction('serverPolling/started')

listenerMiddleware.startListening({
  actionCreator: eventPollingStarted,
  effect: async (action, listenerApi) => {
    // Stop listening for this action
    listenerApi.unsubscribe()

    const pollingTask = listenerApi.fork(async (forkApi) => {
      try {
        // Cancellation-aware indefinite pause
        await forkApi.pause(new Promise(() => {}))
      } catch (err) {
        if (err instanceof TaskAbortError) {
          // Never runs
          console.log('pollingTask aborted')
        }
      }
    })

    try {
      // Wait indefinitely
      await listenerApi.condition(() => false)
      pollingTask.cancel()
    } catch (err) {
      if (err instanceof TaskAbortError) {
        // Never runs
        console.log('top-level task aborted')
      }
    }
  },
})

store.dispatch(eventPollingStarted())

// Some time later, while the tasks are still running, call clearListeners.
setTimeout(() => {
  listenerMiddleware.clearListeners()
}, 500);

Copy link

codesandbox bot commented Oct 9, 2025

Review or Edit in CodeSandbox

Open the branch in Web EditorVS CodeInsiders

Open Preview

Copy link

codesandbox-ci bot commented Oct 9, 2025

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Latest deployment of this branch, based on commit 8c25944:

Sandbox Source
@examples-query-react/basic Configuration
@examples-query-react/advanced Configuration
@examples-action-listener/counter Configuration
rtk-esm-cra Configuration

Copy link

netlify bot commented Oct 9, 2025

Deploy Preview for redux-starter-kit-docs ready!

Name Link
🔨 Latest commit 8c25944
🔍 Latest deploy log https://app.netlify.com/projects/redux-starter-kit-docs/deploys/68e80f7ada7eee0007e346e2
😎 Deploy Preview https://deploy-preview-5102--redux-starter-kit-docs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant